(function() {
    'use strict';

    angular.module('weApp.controllers')
            /**
             * 线路详情页面
             * @param  {[type]} $scope     [description]
             * @param  {[type]} $rootScope [description]
             * @param  {[type]} $state     [description]
             * @param  {[type]} $timeout   [description]
             * @param  {String}            [description]
             * @return {[type]}            [description]
             */
            .controller('lineCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', '$ionicLoading', 'localStorageService', 'myFavorsService', '$interval', '$ionicScrollDelegate', '$ionicGesture',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, $ionicLoading, localStorageService, myFavorsService, $interval, $ionicScrollDelegate, $ionicGesture) {


                    $scope.orientationchange = false;

                    if (!$rootScope.refreshPerSec)
                        $rootScope.refreshPerSec = 6250;

                    $scope.docHeight = document.documentElement.clientHeight;
                    $scope.autoHeight = $scope.docHeight - 260;
                    if ($scope.docHeight <= 480) {
                        $scope.scaleSmall = true;
                    }

                    //这里根据上下行重构起止时间
                    $scope.rebuildData = function(data) {
                        if (!angular.isObject(data))
                            return;
                        //默认值为上行
                        data.evalStartBusTime = data.firstBusTime;
                        data.evalEndBusTime = data.lastBusTime;
                        //下行替换
                        // if( data.lineType === 2 ){
                        //     data.evalStartBusTime = data.downFirstBusTime.trimSpace() == "" ? data.firstBusTime : data.downFirstBusTime;
                        //     data.evalEndBusTime = data.downLastBusTime.trimSpace() == "" ? data.lastBusTime : data.downLastBusTime;
                        // }
                        if (data.lineType === 2) {
                            if (angular.isUndefined(data.downFirstBusTime) || angular.isUndefined(data.downLastBusTime)) {
                                data.evalStartBusTime = data.firstBusTime;
                                data.evalEndBusTime = data.lastBusTime;
                            } else {
                                data.evalStartBusTime = data.downFirstBusTime.trimSpace() == "" ? data.firstBusTime : data.downFirstBusTime;
                                data.evalEndBusTime = data.downLastBusTime.trimSpace() == "" ? data.lastBusTime : data.downLastBusTime;
                            }
                        }
                    };

                    /**
                     * Local Favors init
                     */
                    $scope.myFavors = $scope.myFavorsJSON = null;

                    if (sessionStorage.getItem('clickLine') && sessionStorage.getItem('clickLine') != '') {
                        $scope.lineData = JSON.parse(sessionStorage.getItem('clickLine'));
                        $scope.rebuildData($scope.lineData);
                        $scope.stationName = sessionStorage.getItem('nowLineName');
                        $rootScope.lineData = $scope.lineData;
                    } else {
                        $state.go('index');
                    }

                    /**
                     * 供直线图指令调取的方法
                     * 更新lineData;
                     * @return {[type]} [description]
                     */
                    $scope.getLineDataFromMap = function() {
                        $scope.lineData = JSON.parse(sessionStorage.getItem('clickLine'));
                        $scope.rebuildData($scope.lineData);
                    }

                    /**
                     * 是否存在用户收藏的线路
                     * $scope.myFavors [Array] 收藏 数组 <ID>
                     * $scope.myFavorsJSON [JSON Array] 收藏 数组 <JSON data>
                     * 这里需要将两个属性< myFavors > < myFavorsJSON > 初始化完毕
                     */
                    if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                        $scope.myFavors = JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = JSON.parse(localStorageService.get("myFavorsJSON"));
                    } else {
                        //如果没有任何收藏数据，则直接存入浏览器空数据
                        localStorageService.set("myFavors", null);
                        localStorageService.set("myFavorsJSON", null);
                        $scope.myFavors = [];
                        $scope.myFavorsJSON = [];
                    }

                    /**
                     * 页面每次进入时读取一下本地收藏
                     * @param  {[type]} event [description]
                     * @param  {[type]} data  ){                      $scope.myFavors [description]
                     * @return {[type]}       [description]
                     */
                    $scope.$on("$ionicView.beforeEnter", function(event, data) {
                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    });
                    // console.log( $rootScope.prevState.name )
                    //根据上一级菜单设置当前返回按钮的提示
                    switch ($rootScope.prevState.name) {
                        case 'index' :
                            $scope.prevPage = '首页';
                            break;
                        case 'station' :
                            $scope.prevPage = '站点';
                            break;
                        case 'favor' :
                            $scope.prevPage = '我的收藏';
                            break;
                        case 'searchRes' :
                            $scope.prevPage = '搜索结果';
                            break;
                        case 'transfer' :
                            $scope.prevPage = '线路换乘';
                            break;
                        case 'more' :
                            $scope.prevPage = '更多';
                            break;
                        case 'line' :
                            $scope.prevPage = '线路';
                            break;
                        default:
                            $scope.prevPage = '首页';
                            break;
                    }
                    ;

                    $scope.backToIndex = function() {

                        if ($rootScope.prevState.name) {
                            $state.go($rootScope.prevState, {searchText: $stateParams.searchText});
                        } else {
                            $state.go('index');
                        }

                    };
                    var req = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/line/station/infos'
                        ,
                        data: {
                            "lineId": $scope.lineData.lineId,
                            "lineType": $scope.lineData.lineType.toString()
                        }
                    };

                    /**
                     * 换向
                     * @return {[type]} [description]
                     */
                    $scope.changeDirection = function() {
                        $ionicLoading.show({
                            template: '读取中...'
                        })
                        //获取当前起止站名
                        var startStation = $scope.lineData.firstStationName;
                        var endtStation = $scope.lineData.lastStationName;


                        //这里的switch是用来测试换向功能，届时数据接入后应直接根据获取的数据来判断
                        switch ($scope.lineData.lineType) {
                            case 1 :
                                req.data.lineType = "2";
                                $interval.cancel($scope.busInterval);
                                $http(req)
                                        .then(function(result) {
                                            if (result.data.head.success == "true") {
                                                $scope.linePreData = result.data.data.lineStations;
                                                $scope.lineData.lineType = 2;
                                                $scope.rebuildData($scope.lineData);
                                                sessionStorage.setItem("clickLine", JSON.stringify($scope.lineData));
                                                $scope.busInterval = $interval(function() {
                                                    $scope.refreshLineMap();
                                                }, $rootScope.refreshPerSec);
                                            } else {
                                                $scope.lineData.tipShown = true;
                                                $scope.lineData.tipContent = "没有找到换向的线路或者该线路为环线.";
                                                $scope.lineData.tipTime = 3000;
                                                $ionicLoading.hide();
                                            }

                                        });
                                break;
                            case 2 :
                                req.data.lineType = "1";
                                $interval.cancel($scope.busInterval);
                                $http(req)
                                        .then(function(result) {
                                            if (result.data.head.success == "true") {
                                                $scope.linePreData = result.data.data.lineStations;
                                                $scope.lineData.lineType = 1;
                                                $scope.rebuildData($scope.lineData);
                                                sessionStorage.setItem("clickLine", JSON.stringify($scope.lineData));
                                                $scope.busInterval = $interval(function() {
                                                    $scope.refreshLineMap();
                                                }, $rootScope.refreshPerSec);
                                            } else {
                                                $scope.lineData.tipShown = true;
                                                $scope.lineData.tipContent = "没有找到换向的线路或者该线路为环线.";
                                                $scope.lineData.tipTime = 3000;
                                                $ionicLoading.hide();
                                            }
                                        });
                                break;
                        }
                        //调换起止站名
                        $scope.lineData.firstStationName = endtStation;
                        $scope.lineData.lastStationName = startStation;

                    }

                    /**
                     * 刷新
                     * @return {[type]} [description]
                     */
                    $scope.refreshLineMap = function() {
                        $scope.$broadcast("refreshStationBus");
                    };

                    $scope.refreshLineMap2 = function() {
                        location.reload();
                    };

                    /**
                     * 评价
                     * @return {[type]} [description]
                     */
                    $scope.assessBus = function() {
                        console.log('assessBus');
                    };

                    $scope.busInterval = $interval(function() {
                        $scope.refreshLineMap();
                    }, $rootScope.refreshPerSec);

                    $scope.$on("$ionicView.beforeLeave", function() {
                        $interval.cancel($scope.busInterval);
                        console.log("定时刷新被移除了.");
                        //在离开前移除遮罩，如果在该页面加载出问题时，可以保证页面专场后不会被错误的遮罩。
                        $ionicLoading.hide();
                    });

                    /**
                     * 点击后将该线路加入本地收藏
                     * 收藏的数据将会被存入本地浏览器的LocalStorage中
                     * @param  {[type]} line  [line JSON Data]
                     * @param  {[type]} event [click event]
                     */
                    $scope.favorLine = function(event) {
                        //线路收藏时可能会因为用户点击任意站点而切换，所以每次需要重新获取line
                        var line = $scope.lineData;
                        //当前点击的lineID;
                        var stationId = line.lineStationId;
                        //如果当前myFavors数组总不含有当前点击的lineID
                        //意为当前点击的线路并未被收藏则执行收藏操作
                        if ($scope.myFavors.indexOf(stationId) == -1) {
                            //通过服务存入LocalStorage
                            myFavorsService.set(line);
                            //存入当前页面临时数组中
                            $scope.myFavors.push(stationId);
                            $scope.lineData.tipShown = true;
                            $scope.lineData.tipContent = '收藏成功';

                        } else {    //移除操作
                            //通过服务移除LocalStorage中的当前线路
                            myFavorsService.remove(line);
                            //移除临时数组中的ID
                            $scope.myFavors.remove(stationId);
                            $scope.lineData.tipShown = true;
                            $scope.lineData.tipContent = '取消收藏成功';
                        }
                        $scope.$broadcast("lineFavosChanged");

                    }

                    /**
                     * 获取当前线路站点信息
                     */
                    $ionicLoading.show({
                        template: '读取中...'
                    }).then(function() {
                        $http(req)
                                .then(function(result) {
                                    if (result.data.head.success == "true") {
                                        $scope.linePreData = result.data.data.lineStations;
                                    } else {
                                        $ionicLoading.hide();
                                        alert("获取当前站点线路出错，请重试，谢谢！");
                                        $state.go("index");
                                        return;
                                    }

                                });
                    });


                    $scope.dragDown = function(event) {
                        var mapTop = $ionicScrollDelegate.$getByHandle("lineMapContent").getScrollPosition().top;
                        if (mapTop > 0) {
                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, mapTop - event.gesture.distance, true);
                        }
                    };

                    $scope.dragUp = function(event) {
                        var mapTop = $ionicScrollDelegate.$getByHandle("lineMapContent").getScrollPosition().top;
                        if (mapTop > 0) {
                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, mapTop + event.gesture.distance, true);
                        }
                    }


                    window.addEventListener("orientationchange", function() {

                        if (window.orientation == -90 || window.orientation == 90) {

                            $ionicGesture.on("dragdown", $scope.dragDown, angular.element("#line-map-scroll"));

                            $ionicGesture.on("dragup", $scope.dragUp, angular.element("#line-map-scroll"));

                        } else {

                            $ionicGesture.off("dragdown", $scope.dragDown, angular.element("#line-map-scroll"));
                            $ionicGesture.off("dragup", $scope.dragUp, angular.element("#line-map-scroll"));

                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, 0, true);

                        }

                    }, false);

                }])

})();